package com.evildog.workspace.gateway.fillter;

import com.evildog.workspace.common.consts.CommonConst;
import com.evildog.workspace.common.util.IpUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * 添加Ip头
 */
@Slf4j
@Component
public class IpFilter implements GlobalFilter, Ordered {

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        // TODO ip 黑名单
        String realIp = IpUtil.getRealIp(exchange.getRequest());
        ServerHttpRequest host = exchange.getRequest().mutate()
                .header(CommonConst.GATEWAY_IP_HEADER, realIp).build();
        ServerWebExchange build = exchange.mutate().request(host).build();
        return chain.filter(build);
    }

    @Override
    public int getOrder() {
        return Ordered.HIGHEST_PRECEDENCE;
    }
}
